import 'dart:math';

import 'package:demo/res/resources.dart';
import 'package:demo/utils/toast.dart';
import 'package:demo/widget/app_bar.dart';
import 'package:flustars/src/sp_util.dart';
import 'package:flutter/material.dart';

class SharedPreferencesPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SharedPreferencesState();
  }
}

class _SharedPreferencesState extends State<SharedPreferencesPage> {
  @override
  void initState() {
    super.initState();
    init();
  }

  void init() async {
    await SpUtil.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: 'Dialog样式',
        elevation: 1,
      ),
      body: Column(
        children: <Widget>[
          Gaps.vGap5,
          Text(
              "Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providinga persistent store for simple data."
          ),
          Gaps.vGap5,
          FlatButton(
            color: Colors.green,
            onPressed: () {
              _save();
            },
            child: new Text(
              "随机保存个数据",
              style: TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ),
          FlatButton(
            color: Colors.green,
            onPressed: () {
              _read();
            },
            child: new Text(
              "读取保存的数据",
              style: TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ),
          FlatButton(
            color: Colors.green,
            onPressed: () {
              _clear();
            },
            child: new Text(
              "清除所有保存的数据",
              style: TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _save() {
    SpUtil.putInt("num", Random().nextInt(100000));
    Toast.show("保存成功");
  }

  void _read() {
    var i = SpUtil.getInt("num", defValue: -1);
    if (i == -1) {
      Toast.show("暂无保存数据");
    } else {
      Toast.show("读取到数据：$i");
    }
  }

  void _clear() {
    SpUtil.clear();
    Toast.show("清除成功");
  }
}
